package com.XinYun.Library.modules.admin.userControl.service;

import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.XinYun.Library.modules.admin.borrowMsg.entity.BorrowMsg;
import com.XinYun.Library.modules.admin.common.JSON.AdminJSON;
import com.XinYun.Library.modules.admin.userControl.dao.UserDao;
import com.XinYun.Library.modules.admin.userControl.entity.UserHistory;
import com.XinYun.Library.modules.admin.userControl.entity.UserInfo;
import com.XinYun.Library.modules.admin.common.AdminReturnCode;
import com.XinYun.Library.modules.admin.common.BasicService;
import com.XinYun.Library.modules.admin.common.SqlMapper;
import com.XinYun.Library.modules.commons.BasicJson;
import com.XinYun.Library.utils.JsonUtil;
import org.apache.poi.ss.formula.functions.T;

import javax.servlet.ServletException;
import java.io.IOException;
import java.sql.Date;
import java.util.ArrayList;
import java.util.List;

public class UserService extends BasicService {

    private UserDao userDao = new UserDao();

    public void getMsg(AdminJSON json, JSONObject jsonObj){
        //解参
        String searchBy = jsonObj.getStr("searchBy");
        String keyword = jsonObj.getStr("keyword");
        String pageSize = jsonObj.getStr("pageSize");
        String pageIndex = jsonObj.getStr("pageIndex");
        String state = jsonObj.getStr("state");
        //校验格式
        if(StrUtil.hasEmpty(pageSize,pageIndex))
            {setMsgCode(json, AdminReturnCode.ERR_EMPTY_PARAM);}
        else if(!(Validator.isNumber(pageSize) && Validator.isNumber(pageIndex)))
            {setMsgCode(json, AdminReturnCode.ERR_WRONG_PARAM);}
        else {
            //无错解析为数字继续
            Integer pagesize = Integer.valueOf(pageSize);
            Integer pageindex = Integer.valueOf(pageIndex);
            //分发请求
            String isSearch = null;
            //不为空
            if(!StrUtil.hasEmpty(searchBy,keyword)){
                keyword = fuzzy(keyword);
                isSearch = switch (state){
                    case "所有"->
                        switch (searchBy) {
                            case "username" -> " WHERE user_info." + searchBy + " LIKE " + "'" + keyword + "'";
                            case "sid" -> " WHERE user_info." + searchBy + " LIKE " + "'" + keyword + "'";
                            default -> null;
                        };
                    case "普通","封禁" ->
                        switch (searchBy) {
                            case "username" -> " AND user_info." + searchBy + " LIKE " + "'" + keyword + "'";
                            case "sid" -> " AND user_info." + searchBy + " LIKE " + "'" + keyword + "'";
                            default -> null;
                        };
                    default -> null;
                };
            }
            //获得用户数据和数据量
            List<UserInfo> users;
            long dataNum = 0;
            switch (state){
                case "所有" : users = getAllMsg(pagesize,pageindex,isSearch);
                    dataNum = getAllMsgNum(isSearch);break;
                case "普通" : users = getNormalMsg(pagesize,pageindex,isSearch);
                    dataNum = getNormalMsgNum(isSearch);break;
                case "封禁" : users = getBannedMsg(pagesize,pageindex,isSearch);
                    dataNum = getBannedMsgNum(isSearch);break;
                default : throw new RuntimeException("NoSuchState");
            }
            //结果判断
            if(users.isEmpty())
            {setMsgCode(json, AdminReturnCode.ERR_REQUEST_OVERRIDE);}
            else {
                json.setData(users);
                json.setDataNum(dataNum);
                setMsgCode(json, AdminReturnCode.SUCCECSS);
            }
        }
    }

    private List<UserInfo> getBannedMsg(int pagesize, int pageindex, String isSearch) {
        return userDao.sqlPageFactory(SqlMapper.GET_BANNEDUSER_MSG,pagesize,pageindex,isSearch);
    }

    private List<UserInfo> getNormalMsg(int pagesize, int pageindex, String isSearch) {
        return userDao.sqlPageFactory(SqlMapper.GET_NORMALUSER_MSG,pagesize,pageindex,isSearch);
    }

    private List<UserInfo> getAllMsg(int pagesize, int pageindex, String isSearch) {
        return userDao.sqlPageFactory(SqlMapper.GET_ALLUSER_MSG,pagesize,pageindex,isSearch);
    }

    private Long getBannedMsgNum(String isSearch) {
        return userDao.getDataNum(SqlMapper.GET_BANNEDUSER_MSG_NUM,isSearch);
    }

    private Long getNormalMsgNum(String isSearch) {
        return userDao.getDataNum(SqlMapper.GET_NORMALUSER_MSG_NUM,isSearch);
    }

    private Long getAllMsgNum(String isSearch) {
        return userDao.getDataNum(SqlMapper.GET_ALLUSER_MSG_NUM,isSearch);
    }

    public <T extends BasicJson> void updateBanState(T json,JSONObject jsonObj) throws ServletException, IOException{
        //解参
        String sid = jsonObj.getStr("sid");
        String banState = jsonObj.getStr("banState");
        //校验格式
        if(StrUtil.hasEmpty(sid,banState))
            {setMsgCode(json, AdminReturnCode.ERR_EMPTY_PARAM);}
        else if(!Validator.isNumber(banState))
            {setMsgCode(json,AdminReturnCode.ERR_WRONG_PARAM);}
        else {
            Integer banstate = Integer.valueOf(banState);
            if(List.of(0,1).contains(banstate)) {
                userDao.updateSqldate(sid,banstate);
                setMsgCode(json,AdminReturnCode.SUCCECSS);
            } else {
                setMsgCode(json,AdminReturnCode.ERR_WRONG_PARAM);
            }
        }
    }

    public <T extends BasicJson> void getHistory(T json,JSONObject jsonObj){
        //解参
        String sid = jsonObj.getStr("sid");
        String pageSize = jsonObj.getStr("pageSize");
        String pageIndex = jsonObj.getStr("pageIndex");
        //校验格式
        if(StrUtil.hasEmpty(sid,pageSize,pageIndex))
             {setMsgCode(json, AdminReturnCode.ERR_EMPTY_PARAM);}
        else if(!Validator.isNumber(sid))
             {setMsgCode(json,AdminReturnCode.ERR_WRONG_PARAM);}
        else {
            List<BorrowMsg> borrowMsgs = userDao.getHistory(sid);
            //结果判断
            if(borrowMsgs.isEmpty()) {
                setMsgCode(json, AdminReturnCode.ERR_REQUEST_OVERRIDE);
            }else{
                //转换为前端易读结果
                List<UserHistory> borrowPrintMsgs = new ArrayList<>();
                for (BorrowMsg msg : borrowMsgs) {
                    borrowPrintMsgs.add(parseToPrint(msg));
                }
                setMsgCode(json, AdminReturnCode.SUCCECSS);
                json.setData(borrowPrintMsgs);
            }
        }
    }

    private UserHistory parseToPrint(BorrowMsg book){
        //转值
        String sid = book.getSid();
        String bid = book.getBid();
        String username = book.getUsername();
        String bookname = book.getBookname();
        String starttime =  null;
        String endtime =  null;
        //处理
        Date Tempt1 = book.getStarttime();
        Date Tempt2 = book.getEndtime();
        if(Tempt1 != null && Tempt2 != null){
            starttime = Tempt1.toString();
            endtime = Tempt2.toString();
        }
        String state = switch (book.getState()){
            case 0 -> "借阅";
            case 1 -> "存留";
            case -1 -> "逾期";
            default -> "未知";
        };
        return new UserHistory(username,sid,bookname,bid,state,starttime,endtime);
    }
}
